package com.sitech.ibnms.util.dao.ibatis;

import com.sitech.dao.BaseDao;
import com.sitech.ibnms.util.JSONUtil;
import com.sitech.ibnms.util.dao.SysDictDao;
import com.sitech.ibnms.util.domain.SysDict;
import com.sitech.ibnms.util.domain.SysDictItem;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author liujhc
 */
public class SysDictDaoImpl extends BaseDao implements SysDictDao {

    private static Log log = LogFactory.getLog(SysDictDaoImpl.class);

    @Override
    public SysDict findSysDictById(String dictId) {
        return (SysDict) querySingle("fingSysDictById", dictId);
    }

    @Override
    public List<SysDictItem> findSysDictItemsById(String dictId) {
        return query("fingSysDictItemsById", dictId);
    }

    @Override
    public List<SysDictItem> findSysDictItemsBySQL(String itemsSql, Map<String, String> paramsMap) {
        if (paramsMap == null) {
            paramsMap = Collections.EMPTY_MAP;
        }
        StringBuilder sqlBuilder = new StringBuilder(itemsSql);
        Pattern pattern = Pattern.compile("#[\\w]+#");
        Matcher matcher = pattern.matcher(sqlBuilder);
        int start = 0;
        while (matcher.find(start)) {
            int end = matcher.end();
            start = matcher.start();            
            String param = paramsMap.get(sqlBuilder.substring(start + 1, end - 1));
            if (param == null) {
                param = "";
            } else {
                param = param.replaceAll("'", "''");
            }
            sqlBuilder.replace(start, end, param);
            sqlBuilder.insert(start, "'");
            end = start + param.length() + 1;
            sqlBuilder.insert(end, "'");
            start = end;
        }
        itemsSql = sqlBuilder.toString();
        return query("fingSysDictItemsBySQL", itemsSql);
    }

    @Override
    public SysDict getSysDict(String dictId, Map paramsMap) {
        SysDict dict = this.findSysDictById(dictId);
        //如果数据字典类型配置了sql，查询内容
        String itemsSql = dict.getItemsSql();
        if (StringUtils.isNotBlank(itemsSql)) {
            try {
                dict.getItems().addAll(this.findSysDictItemsBySQL(itemsSql, paramsMap));
            } catch (Exception e) {
                log.error("数据字典" + JSONUtil.toJSON(dict) + "的itemsSql执行失败！", e);
            }
        } else {
            dict.getItems().addAll(this.findSysDictItemsById(dictId));
        }
        return dict;
    }

    @Override
    public SysDict getSysDict(String dictId) {
        return getSysDict(dictId, null);
    }
}
